#include "Daobase.h"
#include <exception/NpException.h>
#include <string.h>
#include <log/NpLogger.h>

#define MYSQL_SET_UTF8() /*\
  static const char* setCharacter = "set names \'utf8\'"; \
  throwExIf(mysql_real_query(m_conn, setCharacter, strlen(setCharacter)) != 0, SET_CHARACTER_ERROR)*/

using namespace npexception;
using namespace std;

Daobase::Daobase(const MYSQL* conn)
{
  setConn(conn);
}

const char* Daobase::getErrorMsg(const string& sql)
{
  static string msg;
  msg = "";
  msg += mysql_error(m_conn);
  msg += "\t";
  msg += sql;
  return msg.c_str();
}

void Daobase::doDml(const std::string &dml)
{
  MYSQL_SET_UTF8();
  throwExAndDoIf((mysql_real_query(m_conn, dml.c_str(), dml.length()) != 0), DO_DML_ERROR,
                 traceBug(BUG); NpLogger::getInstance()->infoLog(getErrorMsg(dml)));
}

MYSQL_RES* Daobase::doQuery(const std::string &query)
{
  MYSQL_SET_UTF8();
  throwExAndDoIf((mysql_real_query(m_conn, query.c_str(), query.length()) != 0), DO_QUERY_ERROR,
                 traceBug(BUG); NpLogger::getInstance()->infoLog(getErrorMsg(query)));
  return mysql_store_result(m_conn);
}

void Daobase::destoryResult(MYSQL_RES *result)
{
  mysql_free_result(result);
}
